const app = getApp();
const db = wx.cloud.database().collection("crew")
Page({
  data: {
    value: '',
    crewList: [] ,
    enable: false,
    actionText: '',
    searchResult: [], 
    loadingProps: {
      size: '50rpx',
    },
    isEditing: false,
    editId:null,
    name: '',
    opus: '',
    contact: '',
    location: '',
    imgUrl: '',
    tempImgUrl: '', // 用于保存暂存图片路径
    money: '',
    link: '',
    autosize: {
      maxHeight: 120,
      minHeight: 20,
    },
    priceError: false,
  },
  onLoad: function() {
    this.getCrewData(); 
  },

  // 获取演员信息的函数
getCrewData: function() {
  // 从 Cloud 数据库中获取符合特定分类的 crew 表中的数据
  
db.where({
  _openid: app.globalData.user_openid,
  
}).get().then(res => {
    console.log(res.data); // 确保获取到数据
    this.setData({
      crewList: res.data // 将获取的数据设置到页面的数据属性中
    });
  }).catch(err => {
    console.error(err);
  });
},
ready() {
  this.setData({ enable: true });
  setTimeout(() => {
    this.setData({ enable: false });
  }, 1000);
},
onRefresh() {
  this.setData({ enable: true });
  this.getCrewData();
  setTimeout(() => {
    this.setData({ enable: false });
  }, 1500); 
}
,
onScroll(e) {
  const { scrollTop } = e.detail;
  this.setData({ scrollTop });
},

viewDetail(e) {
  const index = e.currentTarget.dataset.index; // 获取点击的<c-filmcard>的索引
  const selectedItem = this.data.crewList[index]; // 获取对应索引的设备信息
  
  // 检查selectedItem是否为undefined或null
  if (!selectedItem) {
    console.error("Selected item is undefined or null");
    return;
  }
  
  console.log(selectedItem._id)
  // 跳转到详细信息页面，并传递选定的设备信息
  wx.navigateTo({
    url: '/pages/film-JJRY-detail/film-JJRY-detail?id=' + selectedItem._id
  });
},

handleDelete(e) {
  const index = e.currentTarget.dataset.index;
  const item = this.data.crewList[index]; 
  const id = item._id;
  
  db.doc(id).remove()
    .then(() => {
      wx.showToast({ title: '删除成功', icon: 'none' });
      this.getCrewData(); 
    })
    .catch(err => {
      wx.showToast({ title: '删除失败', icon: 'none' });
      console.error('Failed to delete item:', err);
    });
},


handleEdit(e) {
  const index = e.currentTarget.dataset.index;
  const item = this.data.crewList[index];

  // Check if the item exists to avoid potential errors
  if (!item) {
    console.error("Selected item is undefined or null");
    return;
  }

  // Update the page data with the selected item's details for editing
  this.setData({
    isEditing: true,
    editId: item._id,
    name: item.name,
    opus: item.opus,
    contact: item.contact,
    location: item.location,
    imgUrl: item.picture_url, // Current image URL
    oldImgUrl: item.picture_url, // Save old image URL for potential deletion
    money: item.money,
    link: item.link
  });
},



handleUpload() {
  let that = this;
  wx.chooseImage({
    success: chooseResult => {
      wx.showLoading({
        title: '上传中',
      });
      // 将图片上传至云存储空间
      wx.cloud.uploadFile({
        // 指定上传到的云路径
        cloudPath: 'crew/' + (new Date()).valueOf() + '.png',
        // 指定要上传的文件的小程序临时文件路径
        filePath: chooseResult.tempFilePaths[0],
        // 成功回调
        success: res => {
          console.log('上传成功', res);
          wx.hideLoading();
          wx.showToast({
            title: '上传图片成功',
          });
          if (res.fileID) {
            // 删除旧图片
            if (that.data.oldImgUrl) {
              wx.cloud.deleteFile({
                fileList: [that.data.oldImgUrl],
                success: deleteRes => {
                  console.log('旧图片删除成功', deleteRes);
                },
                fail: err => {
                  console.error('旧图片删除失败', err);
                }
              });
            }
            that.setData({
              zhaopian: '图片如下',
              imgUrl: res.fileID
            });
          }
        },
        fail: err => {
          wx.hideLoading();
          console.error('上传失败', err);
          wx.showToast({
            title: '上传失败，请重试',
            icon: 'none'
          });
        }
      });
    },
    fail: err => {
      console.error('选择图片失败', err);
      wx.showToast({
        title: '选择图片失败，请重试',
        icon: 'none'
      });
    }
  });
},


publishRent() {
  const { editId, name, opus, imgUrl, location, contact, money,  link } = this.data;
  
  // Check if required fields are filled
  if (!name  || !imgUrl || !location || !contact || !money  ) {
    wx.showToast({
      title: '请填写完整信息',
      icon: 'error'
    });
    return;
  }
  
  // Update database
  db.doc(editId).update({
    data: {
      name: name,
      opus:opus,
      picture_url: imgUrl,
      location: location,
      contact: contact,
      money: money,
      link: link
    }
  }).then(() => {
    wx.showToast({ title: '修改成功', icon: 'none' });
    this.setData({
      isEditing: false,
      editId: null,
      name: '',
      imgUrl: '',
      location: '',
      contact: '',
      money: '',
      opus: '',
      link: ''
    });
    this.getCrewData(); // Refresh equipment data after edit
  }).catch(err => {
    wx.showToast({ title: '修改失败，请重试', icon: 'none' });
    console.error('修改失败:', err);
  });
},

cancelEdit() {
  this.setData({
    isEditing: false,
    editId: null,
    
  });
}
 
});